import { useState } from "react";

export default function AddTodo({ onAddTodo }) {
  const [title, setTitle] = useState('');

  const handleAddTodo = () => {
    setTitle('');
    onAddTodo(title);
  }

  const handleKeyDown = (e) => { 
    // 回车键添加任务
    if (e.keyCode === 13 && title.trim()) {
      handleAddTodo();
    }
  }

  return (
    <div>
      <input type="text" value={title}
        onKeyDown={(e) => handleKeyDown(e)}
        onChange={e => setTitle(e.target.value)} />
      <button style={{ marginLeft: '15px' }} onClick={handleAddTodo}>添加</button>
    </div>
  )
}
